<template>
  <div class="home-container">
    <!-- 欢迎横幅 -->
    <el-card class="welcome-banner">
      <div class="banner-content">
        <h1>欢迎光临</h1>
        <p>{{ greeting }}</p>
        <el-button type="primary" size="large" @click="goToMenu">
          立即点餐
        </el-button>
      </div>
    </el-card>

    <!-- 个性化推荐 -->
    <div class="section">
      <div class="section-header">
        <h2>为您推荐</h2>
        <el-tooltip content="根据您的口味偏好推荐">
          <el-icon><InfoFilled /></el-icon>
        </el-tooltip>
      </div>
      
      <el-carousel :interval="5000" arrow="always" height="400px">
        <el-carousel-item v-for="group in groupedRecommendedDishes" :key="group[0].ID">
          <el-row :gutter="20">
            <el-col 
              v-for="dish in group" 
              :key="dish.ID" 
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="6"
            >
              <el-card :body-style="{ padding: '0px' }" class="dish-card" @click="showDishDetail(dish)">
                <img :src="dish.image_url || 'default-dish.jpg'" class="dish-image">
                <div class="dish-info">
                  <h3>{{ dish.name }}</h3>
                  <div class="dish-tags">
                    <el-tag 
                      v-for="tag in dish.tags" 
                      :key="tag" 
                      size="small" 
                      style="margin-right: 5px"
                    >
                      {{ tag }}
                    </el-tag>
                  </div>
                  <div class="dish-price">
                    ¥{{ dish.price }}
                  </div>
                  <div class="dish-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click.stop="addToCart(dish)"
                    >
                      加入购物车
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 热门菜品 -->
    <div class="section">
      <div class="section-header">
        <h2>热门菜品</h2>
        <el-tag type="danger">HOT</el-tag>
      </div>
      
      <el-carousel :interval="5000" arrow="always" height="400px">
        <el-carousel-item v-for="group in groupedPopularDishes" :key="group[0].ID">
          <el-row :gutter="20">
            <el-col 
              v-for="dish in group" 
              :key="dish.ID" 
              :xs="24" 
              :sm="12" 
              :md="8" 
              :lg="6"
            >
              <el-card :body-style="{ padding: '0px' }" class="dish-card" @click="showDishDetail(dish)">
                <img :src="dish.image_url || 'default-dish.jpg'" class="dish-image">
                <div class="dish-info">
                  <h3>{{ dish.name }}</h3>
                  <div class="dish-price">
                    ¥{{ dish.price }}
                  </div>
                  <div class="dish-actions">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click.stop="addToCart(dish)"
                    >
                      加入购物车
                    </el-button>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-carousel-item>
      </el-carousel>
    </div>

    <!-- 购物车悬浮按钮 -->
    <div class="cart-fab">
      <el-badge :value="cartItemCount" :hidden="cartItemCount === 0">
        <el-button 
          type="primary" 
          size="large" 
          circle
          @click="cartDrawer = true"
        >
          <el-icon><ShoppingCart /></el-icon>
        </el-button>
      </el-badge>
    </div>

    <!-- 购物车抽屉 -->
    <el-drawer
      v-model="cartDrawer"
      title="购物车"
      direction="rtl"
      size="400px"
    >
      <div class="cart-content">
        <el-empty v-if="!cartItems.length" description="购物车是空的" />
        <template v-else>
          <div class="cart-items">
            <div v-for="item in cartItems" :key="item.ID" class="cart-item">
              <el-checkbox 
                v-model="item.Selected"
                @change="updateCartItemSelection(item)"
              />
              <img 
                :src="item.Dish.image_url || '/default-dish.jpg'" 
                class="cart-item-image"
              />
              <div class="cart-item-info">
                <h4>{{ item.Dish.name }}</h4>
                <div class="cart-item-price">¥{{ item.Price }}</div>
                <div class="cart-item-actions">
                  <el-input-number 
                    v-model="item.Quantity" 
                    @change="updateCartItemQuantity(item)"
                    :min="1"
                    size="small"
                  />
                  <el-button 
                    type="danger" 
                    icon="Delete"
                    circle
                    @click="removeFromCart(item)"
                  />
                </div>
              </div>
            </div>
          </div>
          <div class="cart-footer">
            <el-checkbox 
              v-model="selectAll"
              @change="toggleSelectAll"
              class="cart-select-all"
            >
              全选
            </el-checkbox>
            <div class="cart-total">
              <span>已选 {{ selectedCount }} 件</span>
              <span>合计: <span class="total-price">¥{{ totalPrice }}</span></span>
            </div>
            <el-button 
              type="primary" 
              :disabled="selectedCount === 0"
              @click="submitOrder"
            >
              提交订单
            </el-button>
          </div>
        </template>
      </div>
    </el-drawer>

    <!-- 订单表单对话框 -->
    <el-dialog
      v-model="orderFormVisible"
      title="提交订单"
      width="30%"
      :before-close="handleClose"
    >
      <el-form
        ref="orderFormRef"
        :model="orderForm"
        :rules="orderFormRules"
        label-width="80px"
      >
        <el-form-item label="就餐方式" prop="orderType">
          <el-radio-group v-model="orderForm.orderType">
            <el-radio-button label="dine_in">堂食</el-radio-button>
            <el-radio-button label="takeout">外卖</el-radio-button>
          </el-radio-group>
        </el-form-item>
        
        <!-- 只在外卖时显示地址和电话输入框 -->
        <template v-if="orderForm.orderType === 'takeout'">
          <el-form-item label="配送地址" prop="address">
            <el-input 
              v-model="orderForm.address"
              placeholder="请输入配送地址"
            />
          </el-form-item>
          <el-form-item label="联系电话" prop="phone">
            <el-input 
              v-model="orderForm.phone"
              placeholder="请输入联系电话"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="confirmOrder">确认</el-button>
      </template>
    </el-dialog>

    <!-- 添加菜品详情弹窗 -->
    <DishDetail
      v-model="dishDetailVisible"
      :dish="selectedDish"
      @add-to-cart="addToCart"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { InfoFilled, ShoppingCart } from '@element-plus/icons-vue'
import type { Dish, CartItem } from '../types'
import DishDetail from '../components/DishDetail.vue'

const store = useStore()
const router = useRouter()
const recommendedDishes = ref<Dish[]>([])
const popularDishes = ref<Dish[]>([])
const discountDishes = ref<Dish[]>([])
const cartDrawer = ref(false)
const cartItems = ref<CartItem[]>([])
const orderFormVisible = ref(false)
const orderFormRef = ref()
const orderForm = ref({
  orderType: 'dine_in',
  address: '',
  phone: ''
})

const dishDetailVisible = ref(false)
const selectedDish = ref(null)

const orderFormRules = {
  orderType: [{ required: true, message: '请选择就餐方式', trigger: 'change' }],
  address: [{ required: true, message: '请输入配送地址', trigger: 'blur' }],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[0-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 购物车相关计算属性
const selectAll = computed({
  get: () => cartItems.value.every(item => item.Selected),
  set: (value) => {
    cartItems.value.forEach(item => item.Selected = value)
  }
})

const selectedCount = computed(() => cartItems.value.filter(item => item.Selected).length)

const totalPrice = computed(() => {
  return cartItems.value.reduce((total, item) => {
    if (item.Selected) {
      return total + item.Quantity * item.Price
    }
    return total
  }, 0)
})

const cartItemCount = computed(() => cartItems.value.reduce((count, item) => count + item.Quantity, 0))

const greeting = computed(() => {
  const hour = new Date().getHours()
  if (hour < 11) return '早上好，来份早餐吧'
  if (hour < 14) return '午好，这里有多款美味套餐'
  if (hour < 17) return '下午好，来份下午茶怎么样'
  if (hour < 22) return '晚上好，精选夜宵等您来'
  return '夜深了，来份宵夜吧'
})

// 根据屏幕宽度计算每页显示数量
const getItemsPerPage = () => {
  const width = window.innerWidth
  if (width >= 1400) return 4      // 大屏幕显示4个
  if (width >= 1200) return 3      // 中大屏幕显示3个
  if (width >= 768) return 2       // 平板显示2个
  return 1                         // 手机显示1个
}

// 将菜品数组分组
const groupDishes = (dishes: Dish[]) => {
  const itemsPerPage = getItemsPerPage()
  const groups = []
  for (let i = 0; i < dishes.length; i += itemsPerPage) {
    groups.push(dishes.slice(i, i + itemsPerPage))
  }
  return groups
}

// 计算属性：分组后的推荐菜品
const groupedRecommendedDishes = computed(() => {
  return groupDishes(recommendedDishes.value)
})

// 计算属性：分组后的热门菜品
const groupedPopularDishes = computed(() => {
  return groupDishes(popularDishes.value)
})

// 监听窗口大小变化
window.addEventListener('resize', () => {
  // 强制重新计算分组
  groupedRecommendedDishes.value = groupDishes(recommendedDishes.value)
  groupedPopularDishes.value = groupDishes(popularDishes.value)
})

// 加载推荐菜品
const loadRecommendedDishes = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/dishes/recommended', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    console.log('Recommended dishes data from API:', data)
    if (response.ok) {
      recommendedDishes.value = data.dishes
    }
  } catch (error) {
    ElMessage.error('加载推荐菜品失败')
  }
}

// 加载热门菜品
const loadPopularDishes = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/dishes/popular', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    console.log('Popular dishes data from API:', data)
    if (response.ok) {
      popularDishes.value = data.dishes
    } else {
      ElMessage.error(data.error || '获取热门菜品失败')
    }
  } catch (error) {
    ElMessage.error('获取热门菜品失败')
  }
}

// // 加载特惠菜品
// const loadDiscountDishes = async () => {
//   try {
//     const response = await fetch('http://localhost:8080/api/dishes/discounts', {
//       headers: {
//         'Authorization': `Bearer ${store.state.token}`
//       }
//     })
//     const data = await response.json()
//     if (response.ok) {
//       discountDishes.value = data.dishes
//     }
//   } catch (error) {
//     ElMessage.error('加载特惠菜品失败')
//   }
// }

// 购物车相关方法
const loadCart = async () => {
  try {
    const response = await fetch('http://localhost:8080/api/cart', {
      headers: {
        'Authorization': `Bearer ${store.state.token}`
      }
    })
    const data = await response.json()
    if (response.ok) {
      cartItems.value = data.items.map((item: CartItem) => ({
        ...item,
        Selected: true
      }))
    }
  } catch (error) {
    ElMessage.error('加载购物车失败')
  }
}

const addToCart = async (dish: Dish) => {
  try {
    const response = await fetch('http://localhost:8080/api/cart', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        dish_id: dish.ID,
        quantity: 1,
        price: dish.price
      })
    })
    if (response.ok) {
      ElMessage.success('添加到购物车成功')
      loadCart()
    }
  } catch (error) {
    ElMessage.error('添加到购物车失败')
  }
}

const updateCartItemQuantity = async (item: CartItem) => {
  try {
    const response = await fetch(`http://localhost:8080/api/cart/${item.ID}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        quantity: item.Quantity,
        selected: item.Selected
      })
    })
    if (!response.ok) {
      ElMessage.error('更新购物车失败')
    }
  } catch (error) {
    ElMessage.error('更新购物车失败')
  }
}

const updateCartItemSelection = async (item: CartItem) => {
  try {
    const response = await fetch(`http://localhost:8080/api/cart/${item.ID}`, {
      method: 'PUT',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        quantity: item.Quantity,
        selected: item.Selected
      })
    })
    if (!response.ok) {
      ElMessage.error('更新选中状态失败')
    }
  } catch (error) {
    ElMessage.error('更新选中状态失败')
  }
}

const removeFromCart = async (item: CartItem) => {
  try {
    const response = await fetch(`http://localhost:8080/api/cart/${item.ID}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${store.state.token}`,
        'Content-Type': 'application/json'
      }
    })
    if (response.ok) {
      ElMessage.success('移除成功')
      loadCart()
    } else {
      ElMessage.error('移除失败')
    }
  } catch (error) {
    ElMessage.error('移除失败')
  }
}

const toggleSelectAll = async (val: boolean) => {
  try {
    await Promise.all(cartItems.value.map(item => 
      fetch(`http://localhost:8080/api/cart/${item.ID}`, {
        method: 'PUT',
        headers: {
          'Authorization': `Bearer ${store.state.token}`,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          quantity: item.Quantity,
          selected: val
        })
      })
    ))
    cartItems.value.forEach(item => item.Selected = val)
  } catch (error) {
    ElMessage.error('更新选中状态失败')
  }
}

const submitOrder = () => {
  const selectedItems = cartItems.value.filter(item => item.Selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要购买的商品')
    return
  }
  orderForm.value = {
    orderType: 'dine_in',
    address: '',
    phone: ''
  }
  orderFormVisible.value = true
}

const confirmOrder = async () => {
  if (!orderFormRef.value) return
  
  const selectedItems = cartItems.value.filter(item => item.Selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要购买的商品')
    return
  }
  
  await orderFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        const response = await fetch('http://localhost:8080/api/orders', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${store.state.token}`,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            order_type: orderForm.value.orderType,
            address: orderForm.value.orderType === 'takeout' ? orderForm.value.address : '',
            phone: orderForm.value.orderType === 'takeout' ? orderForm.value.phone : '',
            items: selectedItems.map(item => ({
              dish_id: item.DishID,
              quantity: item.Quantity,
              price: item.Price
            }))
          })
        })
        
        if (response.ok) {
          ElMessage.success('下单成功')
          orderFormVisible.value = false
          cartDrawer.value = false
          
          const selectedIds = selectedItems.map(item => item.ID)
          await fetch('http://localhost:8080/api/cart', {
            method: 'DELETE',
            headers: {
              'Authorization': `Bearer ${store.state.token}`,
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              item_ids: selectedIds
            })
          })
          loadCart()
        } else {
          const error = await response.json()
          throw new Error(error.error || '下单失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '下单失败')
      }
    }
  })
}

const handleClose = () => {
  orderFormVisible.value = false
}

const goToMenu = () => {
  router.push('/menu')
}

const showDishDetail = (dish: any) => {
  selectedDish.value = dish
  dishDetailVisible.value = true
}

onMounted(() => {
  loadRecommendedDishes()
  loadPopularDishes()
  // loadDiscountDishes()
  loadCart()
})
</script>

<style scoped>
.home-container {
  padding: 20px;
}

.welcome-banner {
  margin-bottom: 40px;
  background: linear-gradient(135deg, #1890ff 0%, #36cfc9 100%);
  color: white;
}

.banner-content {
  padding: 40px;
  text-align: center;
}

.banner-content h1 {
  font-size: 36px;
  margin-bottom: 20px;
}

.section {
  margin-bottom: 40px;
}

.section-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  margin: 0;
  margin-right: 10px;
}

.dish-card {
  height: 100%;
  margin-bottom: 0;  /* 移除底部边距，因为在轮播中 */
  transition: all 0.3s;
}

.dish-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.dish-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.dish-info {
  padding: 16px;
}

.dish-info h3 {
  margin: 0 0 12px;
  font-size: 16px;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.dish-tags {
  margin: 8px 0;
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.dish-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin: 12px 0;
}

.dish-actions {
  display: flex;
  justify-content: flex-end;
}

.carousel-dish {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.carousel-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20px;
  background: rgba(0, 0, 0, 0.7);
  color: white;
}

.discount-card {
  text-align: center;
  background: #fff8f8;
}

.discount-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: #f56c6c;
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
}

.price-info {
  margin: 10px 0;
}

.original-price {
  text-decoration: line-through;
  color: #999;
  margin-right: 10px;
}

.current-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
}

.cart-fab {
  position: fixed;
  right: 40px;
  bottom: 40px;
  z-index: 1000;
}

.cart-badge :deep(.el-badge__content) {
  background-color: #f56c6c;
}

.cart-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.cart-items {
  flex: 1;
  overflow-y: auto;
  padding: 0 20px;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.cart-item-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  margin: 0 10px;
  border-radius: 4px;
}

.cart-item-info {
  flex: 1;
  margin-right: 10px;
}

.cart-item-info h4 {
  margin: 0;
  font-size: 14px;
}

.cart-item-price {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 4px;
}

.cart-item-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.cart-footer {
  border-top: 1px solid #eee;
  padding: 20px;
  background: #fff;
}

.cart-select-all {
  margin-bottom: 10px;
}

.cart-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin-left: 10px;
}

/* 响应式布局断点 */
@media screen and (max-width: 1400px) {
  .el-col-lg-6 {
    width: 25%;
  }
}

@media screen and (max-width: 1200px) {
  .el-col-md-8 {
    width: 33.33%;
  }
}

@media screen and (max-width: 768px) {
  .el-col-sm-12 {
    width: 50%;
  }
}

@media screen and (max-width: 480px) {
  .el-col-xs-24 {
    width: 100%;
  }
}

.el-carousel__item {
  padding: 20px 0;
}
</style> 